package com.ecactus.androidappframework.mvvm2.viewModel;

import android.app.Application;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.Observer;

import com.ecactus.androidappframework.databinding.ActivityUserBinding;
import com.ecactus.androidappframework.mvvm2.model.User;
import com.ecactus.androidappframework.mvvm2.model.UserBusiness;

public class UserViewModel extends AndroidViewModel implements UserBusiness.UserListener, Observer<User> {
    private UserBusiness mUserBusiness = UserBusiness.get();
    private UserLiveData mUserLiveData;
    private User mUser;

    public UserViewModel(@NonNull Application application) {
        super(application);
    }

    public void observe(LifecycleOwner owner, ActivityUserBinding binding) {
        // 加载数据库缓存中的用户信息
        mUser = mUserBusiness.getUser();
        if(mUser == null) {
            mUser = new User();
        }

        binding.setUser(mUser);
        binding.setHost(this);

        mUserLiveData = new UserLiveData();
        // LiveData注册对Activity的监听，同时Activity注册对LiveData的监听
        mUserLiveData.observe(owner, this);
        // 更新LiveData中的数据
        mUserLiveData.postValue(mUser);

        mUserBusiness.addListener(this);
    }

    @Override
    protected void onCleared() {
        Log.i("UserViewModel", "onCleared");
        mUserBusiness.removeListener(this);
        super.onCleared();
    }

    @Override
    public void onRequestUserResult(int code, User user) {
        if(code == 0) {
            // 更新LiveData中的数据
            mUserLiveData.postValue(user);
        } else {
            Toast.makeText(getApplication(), "刷新失败", Toast.LENGTH_SHORT).show();
        }
    }

    public void onRefresh(View v) {
        mUserBusiness.requestUser();
    }

    @Override
    public void onChanged(@Nullable User user) {
        mUser.setName(user.name);
        mUser.setAge(user.age);
    }
}